package com.Test.com;

import com.Test.com.MessageList;
import com.Test.com.SerialiableMessage;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedList;

public class ServerSendRunnable implements Runnable {
    private Socket accept;
    private LinkedList<SerialiableMessage> accountLists;

    public ServerSendRunnable(Socket accept, LinkedList<SerialiableMessage> accountLists) {
        this.accept = accept;
        this.accountLists = accountLists;
    }

    @Override
    public void run() {
        try {
            System.out.println("*为"+accept.getInetAddress().getHostName()+"创建了一条发送线程!");
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(accept.getOutputStream());
            String ip = accept.getInetAddress().getHostAddress();
            long starttime = System.currentTimeMillis();
            while (true){
                long endtime = System.currentTimeMillis();
                if ((endtime-starttime)%60000<5000) {
                    for (int i = 0; i <accountLists.size() ; i++) {
                        objectOutputStream.writeObject(accountLists.get(i));
                    }
                }
                LinkedList<SerialiableMessage> messagesLinkList = MessageList.gainMessageList();
                for (int i = 0; i <messagesLinkList.size() ; i++) {
                    SerialiableMessage serialiableMessage = messagesLinkList.get(i);
                    if (serialiableMessage.getMessage().equals("exit")) {
                        for (int j = 0; j <accountLists.size() ; j++) {
                            if (accountLists.get(j).getSendUserNmae().equals(serialiableMessage.getSendUserNmae())) {
                                accountLists.remove(j);
                                objectOutputStream.close();
                                break;
                            }
                        }
                        messagesLinkList.remove(i);
                        break;
                    }
                    if (ip.equals(serialiableMessage.getReceiveIp())) {
                        objectOutputStream.writeObject(serialiableMessage);
                        messagesLinkList.remove(i);
                    }
                }
            }
        } catch (IOException e) {
        }
    }
}
